package com.xiaotu.service.Impl;

import com.xiaotu.pojo.Comment;
import com.xiaotu.repository.CommentRepository;
import com.xiaotu.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**基于注解实现Redis缓存
 * 引入Redis后,开启缓存,没有指定缓存组件时   自动从缓存组件列表中选择,  Redis
 */
@Service("redisCommentServiceImpl")
public class RedisCommentServiceImpl implements CommentService {
    @Autowired
    private CommentRepository commentRepository;
    @Override
    @Cacheable(cacheNames = "comment",unless = "#result==null")
    public Comment findById(int comment_id) {
        Optional<Comment> byId = commentRepository.findById(comment_id);
        if (byId.isPresent()){
            return byId.get();
        }
        return null;
    }

    @Override
    @CachePut(cacheNames = "comment",key = "#result.id")
    public Comment updateComment(Comment comment) {
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        return comment;
    }
    @Override
    @CacheEvict(cacheNames = "comment")
    public void deleteComment(Integer comment_id) {
        commentRepository.deleteById(comment_id);
    }

    @Override
    @Caching(cacheable = {@Cacheable(cacheNames = "comment",key = "#id")},put = {@CachePut(cacheNames = "comment",key = "#result.author")})
    public Comment getComment(Integer comment_id) {
        return commentRepository.findById(comment_id).get();
    }
}
